package com.dennytech.tac.ui.activity;

import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
import com.dennytech.tac.R;
import com.dennytech.tac.base.CFListActivity;
import com.dennytech.tac.model.Channel;
import com.dennytech.tac.net.api.ChannelListApi;
import com.dennytech.tac.statistics.Stat;
import com.dennytech.tac.ui.adapter.BasicLoadAdapter;
import com.dennytech.tac.widget.ChannelListItem;

public class ChannelListActivity extends CFListActivity implements
		OnItemClickListener {
	Adapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		adapter = new Adapter();

		Uri uri = getIntent().getData();
		String keyword = uri.getQueryParameter("k");
		if (keyword != null) {
			adapter.keyword = keyword;
		}

		String title = uri.getQueryParameter("title");
		if (title != null) {
			setTitle(title);
		}

		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
	}

	Handler mHandler = new Handler() {
		String keword = "";

		public void handleMessage(android.os.Message msg) {
			if (msg.obj == null) {
				return;
			}

			String k = ((String) msg.obj).trim();
			if (k.equals(this.keword)) {
				return;
			}

			this.keword = k;
			adapter.keyword = k;
			adapter.reset();

			Stat.event("channellist", "channellist_search", k, 0);
		};
	};

	private void onKeywordChanged(String keyword) {
		adapter.cancelLoad();

		String k = keyword.trim();
		mHandler.removeMessages(0);
		if ("".equals(k)) {
			mHandler.sendMessage(mHandler.obtainMessage(0, k));
		} else {
			mHandler.sendMessageDelayed(mHandler.obtainMessage(0, k), 800);
		}
	}

	@Override
	protected void onDestroy() {
		adapter.cancelLoad();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Create the search view
		final SearchView searchView = new SearchView(getSupportActionBar()
				.getThemedContext());
		searchView
				.setQueryHint(getString(R.string.hint_please_input_the_keyword));
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				onKeywordChanged(newText);
				return false;
			}
		});

		menu.add(getString(R.string.action_bar_search))
				.setIcon(R.drawable.ic_search)
				.setActionView(searchView)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_IF_ROOM
								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Object item = adapter.getItem(position);
		if (!(item instanceof Channel)) {
			return;
		}
		
		if (view instanceof ChannelListItem) {
			((ChannelListItem)view).changeChannelStatus();
			sendBroadcast(new Intent(
					"com.dennytech.tac.action.CHANNEL_CHANGED"));
		}

		Stat.event("channellist", "channellist_item_click",
				((Channel) item).getName(), 0);
	}

	class Task extends BasicLoadAdapter.NetworkTask {
		String keyword;

		public Task(Adapter adapter) {
			super(adapter);
		}

		public void setKeyword(String k) {
			if ("".equals(k)) {
				keyword = null;
			} else {
				keyword = k;
			}
		}

		@Override
		public JSONObject doInBackground(Integer... params) {
			((ChannelListApi) api).setKeyword(keyword);
			return ((ChannelListApi) api).query();
		}

		@Override
		protected ChannelListApi creatApi() {
			return new ChannelListApi();
		}

	}

	class Adapter extends BasicLoadAdapter<Channel> {

		String keyword;

		@Override
		public int getCount() {
			if (mData.size() == 0) {
				return 1;
			}
			return super.getCount();
		}

		@Override
		public Object getItem(int position) {
			if (position < mData.size()) {
				return mData.get(position);
			}

			if (mData.size() == 0 && !TextUtils.isEmpty(mEmptyMsg)) {
				return EMPTY;
			}

			return super.getItem(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			if (view instanceof ChannelListItem) {
				Channel channel = (Channel) getItem(position);
				((ChannelListItem) view).setChannel(channel);
			}
			return view;
		}

		@Override
		protected View itemViewForData(View convertView, ViewGroup parent) {
			if (convertView != null && convertView instanceof ChannelListItem) {
				return convertView;
			}

			return LayoutInflater.from(parent.getContext()).inflate(
					R.layout.channel_list_item, parent, false);
		}

		@Override
		public com.dennytech.tac.ui.adapter.BasicLoadAdapter.NetworkTask createTask() {
			Task task = new Task(this);
			if (keyword != null) {
				task.keyword = this.keyword;
			}
			return task;
		}

		@Override
		protected Channel decodeObject(JSONObject object) {
			return Channel.decode(object);
		}

	}
}
